define(
		[ "PDUtilDir/grid", "PDUtilDir/searchBlock", "PDUtilDir/slidebar",
				"PDUtilDir/fileupload/multiFileUpload",
				"PDUtilDir/inputSelect", "PDUtilDir/tool", "PDUtilDir/util", "PDOrgDir/userSupport","PDUtilDir/org/selectOrg","AppPathDir/serviceOrg/userSupport",
            "LocalZTree", "Date", "DateCN", "css!DateCss" ],
		function(Grid, SearchBlock, Slidebar, MFU, inputSelect, Tool, Util,User,SelectOrg,UserS, LocalZTree) {

		var initDatas = {};

	    function init(){
	    	initDictData();
			initQuery();
			SearchBlock.init('searchBlockId');
	    }
	    
		var setScopeData=function (key,value){
			sessionStorage.setItem(key, JSON.stringify(value));
		}
		var getScopeData=function(key){
			var data = JSON.parse(sessionStorage.getItem(key));
			return data;
		}
	    
		var serviceOrgDir = getStaticPath() + '/app/serviceOrg/';
		
		//初始化查询条件值
		var initQuery = function(){
	
			dictSelect("queryProvinceName",null,null,getScopeData('provinces'),getQueryCity);
			dictSelect("queryServiceOrgType",null,null,getScopeData('serviceTypes'),null);
		}
		var getProvince = function() {
			$.ajax({
				url : getServer() + "/flea/hclv/getProvinces.htmls",
				sync:false,
				success : function(data) {
					setScopeData('provinces',data.data);
				}
			});
		}
		var getZone = function(pcode) {
			$.ajax({
				url : getServer() + "/flea/hclv/getZone.htmls",
				data : {
					'pcode' : pcode
				},
				success : function(data) {
					dictSelect("areaName","area",null,data.data,null);
				}
			})
		}
		var getZoneForUpdate = function(pcode,selected) {
			$.ajax({
				url : getServer() + "/flea/hclv/getZone.htmls",
				data : {
					'pcode' : pcode
				},
				success : function(data) {
					dictSelect("areaName","area",selected,data.data,null);
				}
			})
		}
		var getCity = function(pcode) {
			$.ajax({
				url : getServer() + "/flea/hclv/getCity.htmls",
				data : {
					'pcode' : pcode
				},
				success : function(data) {
					dictSelect("cityName","city",null,data.data,getZone);
				}
			})
		}
		var getCityForUpdate = function(pcode,selected) {
			$.ajax({
				url : getServer() + "/flea/hclv/getCity.htmls",
				data : {
					'pcode' : pcode
				},
				success : function(data) {
					dictSelect("cityName","city",selected,data.data,getZone);
				}
			})
		}
		var getQueryCity = function(pcode) {
			$.ajax({
				url : getServer() + "/flea/hclv/getCity.htmls",
				data : {
					'pcode' : pcode
				},
				success : function(data) {
					
					dictSelect("queryCityName","queryCity",null,data.data,getQueryZone);
				}
			})
		}
		var getQueryZone = function(pcode) {

			$.ajax({
				url : getServer() + "/flea/hclv/getZone.htmls",
				data : {
					'pcode' : pcode
				},
				success : function(data) {
					dictSelect("queryZoneName","queryZone",null,data.data,null);
				}
			})
		}
		var initDictData = function(){
		 	getServiceOrgType();
			getProvince();
		}
		var callBackFunction = function(data){
			// console.log("----------callbackFunction--------------");
		}
		var dictSelect = function(placeId,valueId,initSelected,initData,callBack) {
			inputSelect.dropCache();
			inputSelect({
				id : placeId,
				key : {
					id : "dictCode",
					name : "dictName",
					data : "data",
				},
				data : initData,
				simpleData : true,
				// 启用文本搜索
				initData : [ initSelected ],
				searchAble : false,
				// 选择之后回调方法：id，选择的id数组，data，选择的数据数组
				callback : function(id, data) {
					var str = "";
					$.each(data, function(i, n) {
						str += n['dictCode'];
					})
					if(callBack!=null){
						callBack(str);
					}
					
					$("#"+valueId).val(str);
				}
			});
		}

		var getServiceOrgType = function(){
			$.ajax({
				url : getServer() + "/flea/dict/initTree.htmls",
				data : {
					'dictCode' : 'D_SERVICE_ORG'
				},
				success : function(data) {
					setScopeData('serviceTypes',data);
                    initGrid(null);
				}
			});
		}

	    


	    var addUserP = function(data){
	    	// console.log(data);
	    	UserS.showPersonList(data);
	    }

		  var  initGrid=function(queryParam) {
				Grid({
					id : "serviceOrgGridId",
					pageSize : 10,
					index : true,
					multi : true,
					pagination : true,
					cache : false,
					layout : [ {
						name : "机构名称",
						field : "deptName",
						sort : true,
						click : function(e) {
							var data = e.data.row;
							saveOrUpdate(data);
						}
					}, {
						name : "代码",
						field : "deptCode",
						sort : true
					}, {
						name : "电话",
						field : "phone",
						width : "10%"
					}, {
						name : "组织类型",
						field : "serviceType",
						format:function(e){
							var serviceTypes = getScopeData('serviceTypes');
							for(var i=0;i<serviceTypes.length;i++){
								if(serviceTypes[i].dictCode==e.row.serviceType){
									return serviceTypes[i].dictName;
								}
								
							}
						}
					}, {
						name : "状态",
						field : "deleted",
						format:function(e){
							if(e.row.deleted==1){
								return "冻结";
							}else{
								return "正常";
							}
							
							
						}
					}, {
						name : "设置负责人",
						field : "deleted",
						format:function(e){return "添加人员"},
						click : function(e) {
							addUserP(e.data.row);
						}
					}
					],
					toolbar : [ {
						name : "添加",
						icon : "fa fa-plus-circle",
						callback : function(event) {

							saveOrUpdate(null);
						}
					}, {
						name : "删除",
						icon : "fa fa-trash-o",
						callback : function(event) {
							deleteBySelectIds();
						}
					}, {
						name : "冻结",
						icon : "fa fa-trash-o",
						callback : function(event) {
							checkDeleted();
						}
					},
					 {
						name : "解冻",
						icon : "fa fa-trash-o",
						callback : function(event) {
							unCheckDeleted();
						}
					},
					{
						name : "查询",
						icon : "fa fa-search",
						callback : function(event) {
							initGrid(getQueryParam());
						}
					} 
					],
					data : {
						type : "URL",
						value : getServer()
								+ "/flea/hclv/serviceOrg/queryAllServiceOrgPage.htmls",
					},
					queryParam : queryParam
				});

			}
		  
		  var saveOrUpdate = function( oldData) {
				var slidebar = Slidebar({
					size : 'lg',
					url : serviceOrgDir+'views/editServiceOrg.html',
//					close : true,
					afterLoad : function($Panel) {
						var $form = $("#DeptBaseInfoForm");
            validateDeptInfo();
						// 添加
						if (null == oldData) {
							dictSelect("provinceName","province",null,getScopeData('provinces'),getCity);
							dictSelect("serviceOrgTypeName","serviceType",null,getScopeData('serviceTypes'),null);
						} else {
							getAddressByUuId(oldData.deptUuid);
							dictSelect("serviceOrgTypeName","serviceType",oldData.serviceType,getScopeData('serviceTypes'),null);
							Tool.deserialize($form, oldData);
						}

						$("#btn_orgDetpSave").on("click",function() {
											// 表单校验
											/*
											 * if(!$form.valid()){ return; }
											 */
              if(!$form.valid()){
               Util.alert("参数不合法");
                return;
              }
											var serviceOrgBaseInfo = Tool.serialize("DeptBaseInfoForm"); // 序列化表单
											$.ajax({
														url : getServer()+ "/flea/hclv/serviceOrg/saveOrUpdate.htmls",
														data : {
															'model' : JSON.stringify(serviceOrgBaseInfo)
														},
														success : function(data) {
															var grid = Grid.getGrid("serviceOrgGridId");
															if(null!=grid){
																Grid.getGrid("serviceOrgGridId").refresh();
															}
															
															Util.alert('操作成功');
															slidebar.close();
														}
													});
										});

					}
				})

			}
		  var saveOrUpdateDeptMent = function( oldData) {
			  var slidebar = Slidebar({
				  size : 'lg',
				  url : serviceOrgDir+'views/editServiceOrg.html',
//				  close : true,
				  afterLoad : function($Panel) {
					  var $form = $("#DeptBaseInfoForm");
            validateDeptInfo();
					  // 添加

					  if (null == oldData) {
						  dictSelect("provinceName","province",null,getScopeData('provinces'),getCity);
						  dictSelect("serviceOrgTypeName","serviceType",null,getScopeData('serviceTypes'),null);
					  } else {
						  getAddressByUuId(oldData.deptUuid);
						  dictSelect("serviceOrgTypeName","serviceType",oldData.serviceType,getScopeData('serviceTypes'),null);
						  Tool.deserialize($form, oldData);
					  }
					  
					  $("#btn_orgDetpSave").on("click",function() {
						  // 表单校验
						  /*
						   * if(!$form.valid()){ return; }
						   */
              if(!$form.valid()){
                Util.alert("参数不合法");
                return;
              }
						  var serviceOrgBaseInfo = Tool.serialize("DeptBaseInfoForm"); // 序列化表单
						  $.ajax({
							  url : getServer()+ "/flea/hclv/serviceOrg/saveOrUpdateDeptMent.htmls",
							  data : {
								  'model' : JSON.stringify(serviceOrgBaseInfo)
							  },
							  success : function(data) {
								  var grid = Grid.getGrid("serviceOrgGridId");
								  if(null!=grid){
									  Grid.getGrid("serviceOrgGridId").refresh();
								  }
                                  var selectedNodes = LocalZTree.getZTreeObj("orgtree").getSelectedNodes();
                                  LocalZTree.getZTreeObj("orgtree").reAsyncChildNodes(selectedNodes[0], 'refresh', false);
								  Util.alert('操作成功');
								  slidebar.close();
							  }
						  });
					  });
					  
				  }
			  })
			  
		  }
		  
			var deleteBySelectIds = function() {
				var gdata = Grid.getGrid("serviceOrgGridId");
				var selectRows = gdata.getSelectedRow();
				if (null != selectRows) {
					Util.confirm(
									"是否要删除",
									function() {
										var ids = new Array();
										$.each(selectRows, function(index,selectRow) {
											ids.push(selectRow.deptUuid);
										});
										$.ajax({
													url : getServer()+ "/flea/hclv/serviceOrg/deletByIds.htmls",
													method : 'post',
													data : {
														'ids' : JSON.stringify(ids)
													},
													success : function(data) {
														gdata.refresh();
														Util.alert(data.message);
													}
												});
									}, function() {
										return;
									});
				} else {
					Util.alert('请选择要删除的数据！');  
				}
			}
			var deleteChildeDept = function(dept) {
				if (null != dept) {
					Util.confirm(
							"是否要删除:"+dept.deptName,
							function() {
								var ids = new Array();
									ids.push(dept.deptUuid);
								$.ajax({
									url : getServer()+ "/flea/hclv/serviceOrg/deletByIds.htmls",
									method : 'post',
									data : {
										'ids' : JSON.stringify(ids)
									},
									success : function(data) {
                                        var selectedNodes = LocalZTree.getZTreeObj("orgtree").getSelectedNodes();
                                        LocalZTree.getZTreeObj("orgtree").reAsyncChildNodes(selectedNodes[0], 'refresh', false);
										Util.alert(data.message);
									}
								});
							}, function() {
								return;
							});
				} else {
					Util.alert('请选择要删除的数据！');  
				}
			}
			var checkDeleted = function() {
				var gdata = Grid.getGrid("serviceOrgGridId");
				var selectRows = gdata.getSelectedRow();
				if (null != selectRows) {
					Util.confirm(
							"确定是需要冻结吗？",
							function() {
								var ids = new Array();
								$.each(selectRows, function(index,selectRow) {
									ids.push(selectRow.deptUuid);
								});
								$.ajax({
									url : getServer()+ "/flea/hclv/serviceOrg/fronze.htmls",
									method : 'post',
									data : {
										'ids' : JSON.stringify(ids)
									},
									success : function(data) {
										gdata.refresh();
										Util.alert(data.message);
									}
								});
							}, function() {
								return;
							});
				} else {
					Util.alert('请选择要删除的数据！');  
				}
			}
			var unCheckDeleted = function() {
				var gdata = Grid.getGrid("serviceOrgGridId");
				var selectRows = gdata.getSelectedRow();
				if (null != selectRows) {
					Util.confirm(
							"确定是需要解冻吗？",
							function() {
								var ids = new Array();
								$.each(selectRows, function(index,selectRow) {
									ids.push(selectRow.deptUuid);
								});
								$.ajax({
									url : getServer()+ "/flea/hclv/serviceOrg/cancelFronze.htmls",
									method : 'post',
									data : {
										'ids' : JSON.stringify(ids)
									},
									success : function(data) {
										gdata.refresh();
										Util.alert(data.message);
									}
								});
							}, function() {
								return;
							});
				} else {
					Util.alert('请选择要删除的数据！');  
				}
			}
		 
			
			var getAddressByUuId = function(uuid) {
				$.ajax({
					url : getServer() + '/flea/hclv/address/findByReUUid.htmls',
					data : {
						'uuid' : uuid
					},
					async : false,
					success : function(data) {
						var address = data.data;
						var $form = $("#DeptBaseInfoForm");
						Tool.deserialize($form, address);
						if (address != null && null != uuid) {
							$('#addRessId').val(address.id);
							initForUpdateSelect(address.province, address.city, address.area);
						}else{
							dictSelect("provinceName","province",null,getScopeData('provinces'),getCity);
						}
					}
				});
			}

			var initForUpdateSelect = function(province,city,area){
				dictSelect("provinceName","province",province,getScopeData('provinces'),getCity);
				getCityForUpdate(province,city);
				getZoneForUpdate(city,area)
			}

      //部门信息验证
      var validateDeptInfo = function(){
        $("#DeptBaseInfoForm").validate({
          ignore:"",
          rules:{
            deptName:{required:true,maxlength:50},
            deptCode:{
              required:true,
              PD_ZSDX:true,
              maxlength:20,
              remote:{
                type:"POST",
                url: getServer()+"/flea/org/dept/validateDeptCode.htmls",
                data:{
                  deptCode:function(){return $("#deptCode").val();},
                  deptUuid:function(){return $("#deptUuid").val();}
                }
              }
            },
            costCenterCode:{maxlength:32},sort:{digits:true,maxlength:8},deptLevel:{maxlength:20},
            extend1:{maxlength:50},extend2:{maxlength:50},extend3:{maxlength:50},extend4:{maxlength:50},extend5:{maxlength:50},
            extend6:{maxlength:50},extend7:{maxlength:50},extend8:{maxlength:50},extend9:{maxlength:50},extend10:{maxlength:50},
            extend11:{maxlength:50},extend12:{maxlength:50},extend13:{maxlength:50},extend14:{maxlength:50},extend15:{maxlength:50},
            extend16:{maxlength:50},extend17:{maxlength:50},extend18:{maxlength:50},extend19:{maxlength:50},extend20:{maxlength:50}
          },
          messages: {
            deptCode:{
              remote:"部门编号已存在,请重新输入"
            }
          }
        });
        $("#DeptExtendInfoForm").validate({
          ignore:"",
          rules:{
            extend1:{maxlength:50},extend2:{maxlength:50},extend3:{maxlength:50},extend4:{maxlength:50},extend5:{maxlength:50},
            extend6:{maxlength:50},extend7:{maxlength:50},extend8:{maxlength:50},extend9:{maxlength:50},extend10:{maxlength:50},
            extend11:{maxlength:50},extend12:{maxlength:50},extend13:{maxlength:50},extend14:{maxlength:50},extend15:{maxlength:50},
            extend16:{maxlength:50},extend17:{maxlength:50},extend18:{maxlength:50},extend19:{maxlength:50},extend20:{maxlength:50}
          }
        });
      };


			var getQueryParam = function() {
				var param = {
					queryName : $("#queryName").val(),
					queryLevel : $("#queryLevel").val(),
					queryProvince : $("#queryProvince").val(),
					queryCity : $("#queryCity").val(),
					queryZone : $("#queryZone").val(),
				}
				return param;
			}
		    return {
		        init:init,
		        saveOrUpdateDeptMent:saveOrUpdateDeptMent,
		        deleteChildeDept:deleteChildeDept,
		    }
});